package com.iqoo.store.servlet;

import com.iqoo.store.dao.CartDao;
import com.iqoo.store.model.CartItem;
import com.iqoo.store.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/addToCart")
public class AddCartsServlet extends HttpServlet {
    private CartDao cartDao = new CartDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户信息
        User user = (User) request.getSession().getAttribute("user");
        if(user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        int productId = Integer.parseInt(request.getParameter("product_id"));
        int userId = user.getId();

        // 检查购物车中是否已有该商品
        CartItem cartItem = cartDao.findByUserIdAndProductId(userId, productId);
        if(cartItem != null) {
            // 更新数量
            cartItem.setQuantity(cartItem.getQuantity() + 1);
            cartDao.update(cartItem);
        } else {
            // 添加到购物车
            cartItem = new CartItem(userId, productId, 1);
            cartDao.add(cartItem);
        }

        // 重定向到购物车页面
        response.sendRedirect("cart.jsp");
    }
}